#encoding: utf-8
=begin

Usage:      This ruby file will recode & split crmeb original order to small orders sort by temp_id
arguments:  ruby split-orders.rb [start_date start_time backward_hours]
Example:    ruby split-orders.rb 2019-07-09 08:00 24'

=end

load 'split-orders-lib.rb'

def split_app_orders app = 'fc'

    etime = ( ARGV[0] && ARGV[1] ) ? Time.parse("#{ARGV[0]} #{ARGV[1]}") : Time.now
    bhours = ARGV[2] ? ARGV[2].to_i : 1
    stime = etime - bhours*3600 + 1 #leave one second

    @rds = @rds_fc
    dir_name = 'fc4-orders'

    if app == 'fcdev'
        return
        @rds = @rds_fcdev 
        dir_name = 'fcdev-orders'
    end

    if app == 'tt'
        $rds = @rds_tt
        dir_name = 'tt-orders'
    end

    orders = get_orders_ "where status = 0 and paid !=0 and order_code is null" #pay_time >= #{stime.to_i} and pay_time <= #{etime.to_i}" # 对于未付款的订单不做拆分
    splitted_orders = split_orders orders
    orders = get_orders_ "where pay_time >= #{stime.to_i} and pay_time <= #{etime.to_i}" # 对于未付款的订单不做拆分
    register_books orders #强制更新所有订单的分拣单以反应最新变化，只能在分离完成后再更新，否则会漏掉派生出来的订单
    archive_orders_during stime, etime, dir_name #更新文档服务器

end

#tt 暂时不能用，因为里面很多地方crmeb被写死了
['fc', 'fcdev'].each do |app|
    split_app_orders app
end
